//
//  GNTagViewCell.m
//  SuperApp
//
//  Created by wmz on 2021/6/2.
//  Copyright © 2021 chaos network technology. All rights reserved.
//

#import "GNTagViewCell.h"
@interface GNTagViewCell()<UICollectionViewDelegate,UICollectionViewDataSource,HDCollectionViewBaseFlowLayoutDelegate>

@property (nonatomic, strong) NSArray <BaseCellModel*>*tagData;

@property (nonatomic, strong) UICollectionView *tagCollectionView;

@property (nonatomic, strong) UIView *view;

@property (nonatomic, strong) HDCollectionViewVerticalLayout *flowLayout;

@end

@implementation GNTagViewCell

- (void)hd_setupViews{
    self.contentView.backgroundColor = wColor_bg;
    [self.contentView addSubview:self.view];
    [self.contentView addSubview:self.lineView];
    [self.view addSubview:self.tagCollectionView];
}

- (void)updateConstraints{
    
    [self.view mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    [self.tagCollectionView layoutIfNeeded];
    [self.tagCollectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.model.contentInset.left);
        make.right.mas_equalTo(-self.model.contentInset.right);
        make.top.mas_equalTo(self.model.contentInset.top);
        make.height.mas_equalTo(self.model.height?:self.tagCollectionView.collectionViewLayout.collectionViewContentSize.height);
        make.bottom.mas_equalTo(-self.model.contentInset.bottom);
    }];
    self.view.userInteractionEnabled = self.tagCollectionView.userInteractionEnabled = self.model.userEnable;
    [super updateConstraints];
}

- (void)setGNModel:(GNTagViewCellModel *)data{
    self.model = data;
    data.notCacheHeight = YES;
    [self.tagCollectionView layoutIfNeeded];
    self.lineView.hidden = !self.model.lineHidden;
    self.tagCollectionView.backgroundColor = data.collectionViewBgColor;
    self.view.backgroundColor = self.model.backgroundColor;
    NSMutableArray <BaseCellModel*>*marr = [NSMutableArray new];
    for (id data in self.model.dataSource) {
        if ([data isKindOfClass:NSString.class]) {
            BaseCellModel *model = BaseCellModel.new;
            model.title = data;
            [marr addObject:model];
        }else if ([data isKindOfClass:BaseCellModel.class]) {
            [marr addObject:data];
        }
    }
    if (!marr.count && data.showEmpty) {
        BaseCellModel *model = BaseCellModel.new;
        model.title = data.showEmpty;
        [marr addObject:model];
    }
    
    self.flowLayout.minimumInteritemSpacing = data.minimumInteritemSpacing;
    self.flowLayout.minimumLineSpacing = data.minimumInteritemSpacing;
    self.tagData = [NSArray arrayWithArray:marr];
    [self.tagCollectionView reloadData];
    [self.tagCollectionView layoutIfNeeded];
    [self setNeedsUpdateConstraints];
}

#pragma mark delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.model.userEnable) return;
    if (self.model.much) {
        self.tagData[indexPath.row].select = !self.tagData[indexPath.row].isSelected;
        [GNEvent eventResponder:self target:nil key:@"GNTagClick" indexPath:indexPath info:@{@"data":self.tagData[indexPath.row],@"model":self.model}];
    }else{
        for (BaseCellModel *model in self.tagData) {
            if ([model isKindOfClass:BaseCellModel.class]) {
                if (model == self.tagData[indexPath.row]) {
                    model.select = YES;
                    [GNEvent eventResponder:self target:nil key:@"GNTagClick" indexPath:indexPath info:@{@"data":model,@"model":self.model}];
                }else{
                    model.select = NO;
                }
            }
        }
    }
    [collectionView reloadData];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GNTagCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GNTagCollectionViewCell" forIndexPath:indexPath];
    BaseCellModel *cellModel = self.tagData[indexPath.row];
    if (![cellModel valueForKey:@"title"]) return cell;
    cell.contentView.layer.cornerRadius = self.model.cornerRadius;
    [cell.nameLb setTitle:cellModel.title forState:UIControlStateNormal];
    if ([cellModel isKindOfClass:BaseCellModel.class]) {
        if (self.model.history) {
            cell.contentView.layer.backgroundColor = self.model.bgColor.CGColor;
            [cell.nameLb setTitleColor:self.model.textColor forState:UIControlStateNormal];
        }else{
            if (self.model.userEnable) {
                if (!self.model.bgColor) {
                    if (!cellModel.randomColor) {
                        int num = arc4random()%255;
                        cellModel.randomColor =  [UIColor colorWithRed:num/255.0 green:num/255.0 blue:num/255.0 alpha:0.1];
                        cellModel.titleColor = [UIColor colorWithRed:num/255.0 green:num/255.0 blue:num/255.0 alpha:1];
                    }
                    cell.contentView.layer.backgroundColor =  cellModel.randomColor.CGColor;
                    [cell.nameLb setTitleColor:cellModel.titleColor forState:UIControlStateNormal];
                }else{
                    cell.contentView.layer.backgroundColor = cellModel.isSelected? self.model.bgSelectColor.CGColor: self.model.bgColor.CGColor;
                    [cell.nameLb setTitleColor:self.tagData[indexPath.row].isSelected?self.model.textSelectColor:self.model.textColor forState:UIControlStateNormal];
                }
            }else{
                cell.contentView.layer.backgroundColor = self.model.bgColor.CGColor;
                [cell.nameLb setTitleColor:self.tagData[indexPath.row].isSelected?self.model.textSelectColor:self.model.textColor forState:UIControlStateNormal];
            }
        }
        if (cellModel.image) {
            [cell.nameLb setImage:(self.tagData[indexPath.row].isSelected?  (cellModel.selectImage?:cellModel.image):cellModel.image) forState:UIControlStateNormal];
            [cell.nameLb TagSetImagePosition:PostBtnPositionLeft spacing:PostNum(5)];
        }
    }
    if (self.model.showEmpty && (!self.model.dataSource || !self.model.dataSource.count)) {
        [cell.nameLb setTitleColor:wColor_6 forState:UIControlStateNormal];
        cell.contentView.layer.cornerRadius = PostNum(6);
        cell.contentView.layer.borderWidth = 1;
        cell.contentView.layer.borderColor = wColor_6.CGColor;
    }
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.tagData.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    BaseCellModel *model = self.tagData[indexPath.row];
    if (!model.width) {
        model.width = ceilf([model.title boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, PostNum(30)) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: wFontSize(14)} context:nil].size.width);
    }
    CGFloat width = model.width + self.model.space +
    ([model isKindOfClass:BaseCellModel.class] ? (model.image ? PostNum(20) : 0) : 0);
    return CGSizeMake(MIN(PostWidth - PostL * 2 ,width), self.model.itemSizeH);
}

- (Class)yb_classOfCell{
    return GNTagViewCell.class;
}

- (UICollectionView *)tagCollectionView{
    if (!_tagCollectionView) {
        _tagCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, PostWidth - 2*PostL , PostNum(28)) collectionViewLayout:self.flowLayout];
        _tagCollectionView.delegate = self;
        _tagCollectionView.dataSource = self;
        _tagCollectionView.scrollEnabled = NO;
        _tagCollectionView.backgroundColor = UIColor.redColor;
        [_tagCollectionView registerClass:GNTagCollectionViewCell.class forCellWithReuseIdentifier:@"GNTagCollectionViewCell"];
    }
    return _tagCollectionView;
}

- (HDCollectionViewVerticalLayout *)flowLayout{
    if (!_flowLayout) {
        _flowLayout = HDCollectionViewVerticalLayout.new;
        _flowLayout.delegate = self;
    }
    return _flowLayout;
}

- (UIView *)view{
    if (!_view) {
        _view = UIView.new;
        _view.backgroundColor = wColor_bg;
    }
    return _view;
}

@end

@implementation GNTagCollectionViewCell

-  (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self.contentView addSubview:self.nameLb];
        [self.nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.mas_equalTo(3);
            make.right.bottom.mas_equalTo(-3);
        }];
        
        [self.contentView addSubview:self.deleteBTN];
        [self.deleteBTN mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-3);
            make.top.mas_offset(2);
        }];
    }
    return self;
}

- (BaseButton *)nameLb{
    if (!_nameLb) {
        _nameLb = [BaseButton buttonWithType:UIButtonTypeCustom];
        _nameLb.titleLabel.font = wFontSize(14);
        _nameLb.userInteractionEnabled = NO;
    }
    return _nameLb;
}

- (BaseButton *)deleteBTN{
    if (!_deleteBTN) {
        _deleteBTN = [BaseButton buttonWithType:UIButtonTypeCustom];
        _deleteBTN.add_image([UIImage imageNamed:@"common_close"]);
        _deleteBTN.hidden = YES;
    }
    return _deleteBTN;
}

@end
